<script lang="ts" setup>
import type { EchartsUIType } from '@vben/plugins/echarts';

import { onMounted, ref, watch } from 'vue';

import { EchartsUI, useEcharts } from '@vben/plugins/echarts';

// 导入echarts以解决全局变量问题
import * as echarts from 'echarts';

interface CostData {
  maintenanceRatio: number;
  fuelRatio: number;
}

const props = defineProps<{
  data: CostData;
}>();

const chartRef = ref<EchartsUIType>();
const { renderEcharts } = useEcharts(chartRef);

// 监听数据变化，重新渲染图表
watch(
  () => props.data,
  () => {
    renderChart();
  },
  { deep: true },
);

const renderChart = () => {
  if (!props.data) return;

  const chartData = [
    {
      name: '维保成本',
      value: props.data.maintenanceRatio,
      itemStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: '#5ab1ef' },
          { offset: 1, color: '#019680' },
        ]),
      },
    },
    {
      name: '燃油成本',
      value: props.data.fuelRatio,
      itemStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: '#f9c74f' },
          { offset: 1, color: '#f8961e' },
        ]),
      },
    },
  ];

  renderEcharts({
    title: {
      text: '成本构成分析',
      left: 'center',
      top: '5%',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold',
        color: '#333',
      },
    },
    tooltip: {
      trigger: 'item',
      formatter: (params: any) => {
        return `
          <div style="padding: 8px;">
            <div style="font-weight: bold; margin-bottom: 4px; color: ${params.color};">${params.name}</div>
            <div>占比: <span style="color: #5ab1ef;">${params.value}%</span></div>
            <div>金额: <span style="color: #f9c74f;">¥${(params.percent * 10_000).toLocaleString()}</span></div>
          </div>
        `;
      },
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      top: 'center',
      textStyle: {
        color: '#666',
      },
    },
    series: [
      {
        name: '成本构成',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['60%', '50%'],
        data: chartData,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)',
          },
          label: {
            show: true,
            fontSize: '14',
            fontWeight: 'bold',
          },
        },
        label: {
          formatter: '{b}: {d}%',
          fontSize: 12,
        },
        labelLine: {
          show: true,
        },
      },
    ],
    animation: true,
  });
};

onMounted(() => {
  renderChart();
});
</script>

<template>
  <div class="h-full w-full">
    <EchartsUI ref="chartRef" />
  </div>
</template>

<style scoped>
/* 图表容器样式 */
.w-full {
  width: 100%;
}

.h-full {
  height: 100%;
}
</style>
